package cn.tsingyu.antsclub.model;

import java.sql.Timestamp;
import java.util.List;

import cn.tsingyu.antsclub.common.Json;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Record;

@SuppressWarnings("serial")
public class UserActivity extends Model<UserActivity>{
	public static final UserActivity dao = new UserActivity();
	/**
	 * 
	 * @param actId
	 * @param userId
	 * @return user_activity id
	 */
	public UserActivity isSign(String actId,String userId){
		List<UserActivity> list=find("select * from user_activity where activityId=? and userId=?"
									,actId,userId);
		if(list.size()>0){
			return list.get(0);
		}else{
			return null;
		}
	}
	public boolean isSign(Record r,String userId){
		String signIds = r.getStr("signIds");
		for (String signId : signIds.split("，")) {
			if (signId.equals(userId)){
				return true;
			}
		}
		return false;
	}
	public Json checkTime(Record r){
		Json j = new Json();
		Timestamp endTime = r.getTimestamp("endTime");
		Timestamp now = new Timestamp(System.currentTimeMillis());
		if(now.getTime()>=endTime.getTime()){
			j.setSuccess(false);
			j.setMsg("活动已经结束，不能再报名了，欢迎参加下次活动");
		}else{
			j.setSuccess(true);
		}
		return j;
	}
	public Json checkBalance(Record r,String uid,int signNum){
		Json j = new Json();
		Account a = Account.dao.findByUserId(uid);
		Float balance = a.getFloat("balance");
		Float payAmount = r.getFloat("payAmount");
		if(balance<payAmount*signNum){
			j.setSuccess(false);
			j.setMsg("报名未成功，活动是预付费，需要提前支付费用总计"+payAmount*signNum+"元，您的账户余额为"+balance);
		}else{
			j.setSuccess(true);
		}
		return j;
	}
	public int undoSign(String actId,String userId){
		String sql = "DELETE FROM user_activity WHERE activityId = ? and userId=?";
        return Db.update(sql, actId, userId);
	}
}
